#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QBuffer>
#include <QPixmap>
#include <QDateTime>
#include <QtEndian>
#include <QDebug>
#include <QElapsedTimer>
#include <QVBoxLayout>
#include <QDir>
#include <QFile>
#include <QDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint | windowFlags());
    // 从UI获取IP和端口
    currentIp = ui->ipEdit->toPlainText();
    currentPort = ui->portEdit->toPlainText().toUShort();
    // 使用新式Qt信号槽语法（兼容旧版）
    connect(&socket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);

    // 初始化状态（保持原有逻辑）
    ui->statusLabel->setText("Ready");
    serverAddr = QHostAddress("192.168.1.128"); // 实际服务器IP
    serverPort = 8885;

    // 绑定端口（增加错误详情输出）
    if (!socket.bind(serverPort)) {
        ui->statusLabel->setText(tr("端口绑定失败: %1").arg(socket.errorString()));
        qDebug() << "Bind error:" << socket.errorString();
    }

    // 人脸检测模型加载（增加多路径尝试）
    QStringList cascadePaths = {
        "haarcascade_frontalface_alt2.xml",                     // 同级目录
        "D:/opencv/opencv3.4-install/install/etc/haarcascades/haarcascade_frontalface_alt2.xml" // 绝对路径
    };

    bool modelLoaded = false;
    for (const auto &path : cascadePaths) {
        if (faceCascade.load(path.toStdString())) {
            qDebug() << "Loaded cascade from:" << path;
            modelLoaded = true;
            break;
        }
    }

    if (!modelLoaded) {
        qDebug() << "Failed to load face cascade model";
        ui->statusLabel->setText("人脸模型加载失败");
    }

    // 定时器设置（优化检测频率）
    detectionTimer.setInterval(50); // 20fps刷新
    connect(&detectionTimer, &QTimer::timeout, this, [this]() {
        QMutexLocker locker(&imageMutex);
        if (faceDetectionEnabled && !lastProcessedImage.isNull()) {
            // 仅当图像有变化时更新UI
            QPixmap current = QPixmap::fromImage(lastProcessedImage)
                    .scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            if (ui->label->pixmap() && current.cacheKey() != ui->label->pixmap()->cacheKey()) {
                ui->label->setPixmap(current);
            }
        }
    });

    // 初始化自动拍照定时器
    autoPhotoTimer.setInterval(3000); // 3秒
    connect(&autoPhotoTimer, &QTimer::timeout, this, &MainWindow::autoTakePhoto);

    // 初始化相册对话框
    albumDialog = new QDialog(this);
    albumDialog->setWindowTitle("照片相册");
    albumDialog->resize(600, 500);

    QVBoxLayout* layout = new QVBoxLayout(albumDialog);

    // 照片列表
    photoListWidget = new QListWidget(albumDialog);
    photoListWidget->setViewMode(QListWidget::IconMode);
    photoListWidget->setIconSize(QSize(100, 100));
    photoListWidget->setResizeMode(QListWidget::Adjust);
    photoListWidget->setMovement(QListWidget::Static);
    connect(photoListWidget, &QListWidget::itemClicked, this, &MainWindow::showSelectedPhoto);

    // 照片显示区域
    photoDisplayLabel = new QLabel(albumDialog);
    photoDisplayLabel->setAlignment(Qt::AlignCenter);
    photoDisplayLabel->setMinimumSize(400, 300);

    // 添加按钮区域
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    QPushButton* closeButton = new QPushButton("关闭", albumDialog);
    connect(closeButton, &QPushButton::clicked, albumDialog, &QDialog::close);
    buttonLayout->addStretch();
    buttonLayout->addWidget(closeButton);

    layout->addWidget(photoListWidget);
    layout->addWidget(photoDisplayLabel);
    layout->addLayout(buttonLayout);

    albumDialog->setLayout(layout);

    // 加载已有照片
    loadPhotos();

    qDebug() << "UDP client initialized on port" << serverPort;
}

MainWindow::~MainWindow()
{
    detectionTimer.stop();
    autoPhotoTimer.stop();
    delete ui;
}

void MainWindow::readPendingDatagrams()
{
    QMutexLocker locker(&imageMutex); // 保证线程安全

    while (socket.hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket.pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        socket.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        // 协议处理（保持原有逻辑）
        if (datagram.size() == 4 && expectedSize == 0) {
            expectedSize = qFromBigEndian(*reinterpret_cast<const quint32*>(datagram.constData()));
            buffer.clear();
            continue;
        }

        buffer.append(datagram);

        if (expectedSize > 0 && buffer.size() >= expectedSize) {
            QByteArray jpegData = buffer.left(expectedSize);
            buffer.remove(0, expectedSize);
            expectedSize = 0;

            QImage img = QImage::fromData(jpegData, "JPEG");
            if (!img.isNull()) {
                // 核心修改点：统一图像处理管道
                if (faceDetectionEnabled) {
                    lastProcessedImage = detectFaces(img); // 人脸检测处理
                } else {
                    lastProcessedImage = img; // 原始图像通路
                    ui->label->setPixmap(QPixmap::fromImage(img)
                                         .scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
                }

                // 保持原有拍照功能
                if (!streaming && photoRequested) {
                    QString baseName = QString("snapshot_%1").arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"));
                    QString fileName = baseName + ".jpg";

                    // 检查文件名是否已存在，如果存在则添加序号
                    int counter = 1;
                    while (QFile::exists(fileName)) {
                        fileName = QString("%1_%2.jpg").arg(baseName).arg(counter++);
                    }

                    if (img.save(fileName, "JPG", 95)) {
                        ui->statusLabel->setText(tr("已保存: %1").arg(fileName));
                        loadPhotos();  // 刷新相册
                    } else {
                        ui->statusLabel->setText("保存失败");
                    }
                    photoRequested = false;
                }
            }
        }
    }
}

QImage MainWindow::detectFaces(const QImage& img)
{
    QElapsedTimer timer;
    timer.start();

    // 格式转换保障（RGB888 + 深拷贝）
    QImage rgbImg = img.convertToFormat(QImage::Format_RGB888).copy();

    // OpenCV处理管道
    cv::Mat frame(rgbImg.height(), rgbImg.width(), CV_8UC3,
                  (uchar*)rgbImg.bits(), rgbImg.bytesPerLine());

    // 颜色空间转换（Qt RGB -> OpenCV BGR）
    cv::Mat bgrFrame;
    cv::cvtColor(frame, bgrFrame, cv::COLOR_RGB2BGR);

    // 灰度处理 + 直方图均衡
    cv::Mat grayFrame;
    cv::cvtColor(bgrFrame, grayFrame, cv::COLOR_BGR2GRAY);
    cv::equalizeHist(grayFrame, grayFrame);

    // 人脸检测（优化参数）
    std::vector<cv::Rect> faces;
    faceCascade.detectMultiScale(grayFrame, faces,
                                 1.1,    // 缩放因子
                                 4,      // 最小相邻矩形数
                                 cv::CASCADE_SCALE_IMAGE,
                                 cv::Size(60, 60)); // 最小人脸尺寸

    // 绘制检测结果（红色边框，抗锯齿）
    for (const auto& face : faces) {
        cv::rectangle(bgrFrame, face, cv::Scalar(0, 0, 255), 2, cv::LINE_AA);
    }

    // 转换回Qt格式（BGR -> RGB）
    cv::Mat rgbOutput;
    cv::cvtColor(bgrFrame, rgbOutput, cv::COLOR_BGR2RGB);

    qDebug() << "Detected" << faces.size() << "faces in" << timer.elapsed() << "ms";

    return QImage(rgbOutput.data, rgbOutput.cols, rgbOutput.rows,
                  rgbOutput.step, QImage::Format_RGB888).copy();
}

void MainWindow::on_btnStream_clicked()
{
    streaming = true;
    if (socket.writeDatagram("get_stream", serverAddr, serverPort) > 0) {
        ui->statusLabel->setText("视频流请求已发送");
    }
    qDebug() << "Sent stream request";
}

void MainWindow::on_btnPhoto_clicked()
{
    streaming = false;
    photoRequested = true;
    if (socket.writeDatagram("get_photo", serverAddr, serverPort) > 0) {
        ui->statusLabel->setText("拍照请求已发送");
    }
    qDebug() << "Sent photo request";
}

void MainWindow::on_btnFaceDetection_clicked()
{
    faceDetectionEnabled = !faceDetectionEnabled;
    if (faceDetectionEnabled) {
        detectionTimer.start();
        autoPhotoEnabled = true;  // 开启自动拍照功能
        autoPhotoTimer.start();   // 启动自动拍照定时器
        ui->statusLabel->setText("人脸检测已开启");
        qDebug() << "Face detection enabled";
    } else {
        detectionTimer.stop();
        autoPhotoEnabled = false;  // 关闭自动拍照功能
        autoPhotoTimer.stop();     // 停止自动拍照定时器
        ui->statusLabel->setText("人脸检测已关闭");
        qDebug() << "Face detection disabled";
    }
}

void MainWindow::on_btnAlbum_clicked()
{
    loadPhotos();  // 刷新照片列表
    albumDialog->exec();  // 显示相册对话框
}

void MainWindow::loadPhotos()
{
    photoListWidget->clear();

    QDir dir(".");
    QStringList filters;
    filters << "snapshot_*.jpg" << "auto_snapshot_*.jpg";
    QStringList photoFiles = dir.entryList(filters, QDir::Files, QDir::Time);

    foreach (const QString &fileName, photoFiles) {
        QPixmap thumbnail(fileName);
        if (!thumbnail.isNull()) {
            thumbnail = thumbnail.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            QListWidgetItem* item = new QListWidgetItem(QIcon(thumbnail), fileName);
            item->setData(Qt::UserRole, fileName);  // 存储完整文件名
            photoListWidget->addItem(item);
        }
    }
}

void MainWindow::showSelectedPhoto(QListWidgetItem* item)
{
    QString fileName = item->data(Qt::UserRole).toString();
    QPixmap pixmap(fileName);

    if (!pixmap.isNull()) {
        // 缩放以适应显示区域
        QPixmap scaledPixmap = pixmap.scaled(photoDisplayLabel->width(),
                                             photoDisplayLabel->height(),
                                             Qt::KeepAspectRatio,
                                             Qt::SmoothTransformation);
        photoDisplayLabel->setPixmap(scaledPixmap);
    }
}

void MainWindow::autoTakePhoto()
{
    if (!autoPhotoEnabled || lastProcessedImage.isNull()) {
        return;
    }

    QString baseName = QString("auto_snapshot_%1").arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"));
    QString fileName = baseName + ".jpg";

    // 检查文件名是否已存在，如果存在则添加序号
    int counter = 1;
    while (QFile::exists(fileName)) {
        fileName = QString("%1_%2.jpg").arg(baseName).arg(counter++);
    }

    if (lastProcessedImage.save(fileName, "JPG", 95)) {
        ui->statusLabel->setText(tr("自动拍照已保存: %1").arg(fileName));
        loadPhotos();  // 刷新相册
    } else {
        ui->statusLabel->setText("自动拍照保存失败");
    }
}

void MainWindow::on_btnDisconnect_clicked()
{
    if (socket.state() == QAbstractSocket::BoundState) {
        socket.disconnectFromHost();
        socket.close();
        ui->statusLabel->setText("连接已断开");
    }
}

void MainWindow::on_pushButton_2_clicked()
{
    // 每次重连时从UI获取最新的IP和端口
    currentIp = ui->ipEdit->toPlainText();
    currentPort = ui->portEdit->toPlainText().toUShort();

    // 更新服务器地址和端口
    serverAddr = QHostAddress(currentIp);
    serverPort = currentPort;

    if (socket.state() == QAbstractSocket::UnconnectedState) {
        if (!socket.bind(serverPort)) {
            ui->statusLabel->setText(tr("端口绑定失败: %1").arg(socket.errorString()));
            qDebug() << "Bind error:" << socket.errorString();
        } else {
            ui->statusLabel->setText("连接已重新建立");
        }
    }
}
